<template>
  <el-menu
    :default-active="activeMenu"
    mode="horizontal"
    :ellipsis="false"
    @select="handleSelect"
  >
    <template v-for="(item, index) in topMenus">
      <el-menu-item
        v-if="index < visibleNumber"
        :key="index"
        :style="{'--theme': theme}"
        :index="item.path"
      >
        <svg-icon :icon-class="item.meta.icon" />
        {{ item.meta.title }}
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <el-sub-menu v-if="topMenus.length > visibleNumber" :style="{'--theme': theme}" index="more">
      <template #title>更多菜单</template>
      <template v-for="(item, index) in topMenus">
        <el-menu-item
          v-if="index >= visibleNumber"
          :key="index"
          :index="item.path"
        >
          <svg-icon :icon-class="item.meta.icon" />
          {{ item.meta.title }}
        </el-menu-item>
      </template>
    </el-sub-menu>
  </el-menu>
</template>

<script setup>
import router, { constantRoutes } from "@/router"
import SvgIcon from "@/components/GUI/SvgIcon.vue"
import { isHttp } from '@/utils'
import store from '@/store/index.js'

const settingsStore = store.settings
const permissionStore = store.permission
const visibleNumber = ref(5)
const isFirst = ref(true)
const currentIndex = ref(undefined)
const route = useRoute()

// 主题颜色
const theme = computed(() => settingsStore.theme)

// 所有的路由信息
const routers = computed(() => permissionStore.topbarRouters)
// 顶部显示菜单
const topMenus = computed(() => {
  const topMenus = []
  routers.value.map((menu) => {
    if (menu.hidden !== true) {
      // 兼容顶部栏一级菜单内部跳转
      if (menu.path === "/") {
        topMenus.push(menu.children[0])
      } else {
        topMenus.push(menu)
      }
    }
  })
  return topMenus
})

// 设置子路由
const childrenMenus = computed(() => {
  const childrenMenus = []
  routers.value.map((router) => {
    for (const item in router.children) {
      if (router.children[item].parentPath === undefined) {
        if (router.path === "/") {
          router.children[item].path = "/redirect/" + router.children[item].path
        } else {
          if (!isHttp(router.children[item].path)) {
            router.children[item].path = router.path + "/" + router.children[item].path
          }
        }
        router.children[item].parentPath = router.path
      }
      childrenMenus.push(router.children[item])
    }
  })
  return constantRoutes.concat(childrenMenus)
})

// 默认激活的菜单
// 监听路由变化处理isFirst,isFirst设置值后停止监听
const routePathWatch = watch(() => route.path, path => {
  if (path === '/index' || path === '') {
    if (!isFirst.value) {
      isFirst.value = true
      routePathWatch.stop()
    }
  }
})

// computed中只保留纯计算逻辑
const activeMenu = computed(() => {
  const path = route.path
  let activePath = defaultRouter()

  if (path.lastIndexOf('/') > 0) {
    const tmpPath = path.substring(1, path.length)
    activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'))
  } else if (path === '/index' || path === '' && isFirst.value) {
    activePath = 'index'
  }

  const routes = activeRoutes(activePath)
  if (routes.length === 0) {
    activePath = currentIndex.value || defaultRouter()
    activeRoutes(activePath)
  }
  return activePath
})


// 根据宽度计算设置显示栏数
function setVisibleNumber() {
  const width = document.body.getBoundingClientRect().width / 3
  visibleNumber.value = parseInt(width / 85)
}

// 默认激活的路由
function defaultRouter() {
  let router
  Object.keys(routers).some((key) => {
    if (!routers[key].hidden) {
      router = routers[key].path
      return true
    }
  })
  return router
}

function handleSelect(key, keyPath) {
  currentIndex.value = key
  if (isHttp(key)) {
    // http(s):// 路径新窗口打开
    window.open(key, "_blank")
  } else if (key.indexOf('/redirect') !== -1) {
    // 没有子路由路径内部打开
    router.push({path: key.replace('redirect', '')})
  } else {
    // 显示左侧联动菜单
    activeRoutes(key)
  }
}


function activeRoutes(key) {
  const routes = []
  if (childrenMenus.value && childrenMenus.value.length > 0) {
    childrenMenus.value.map((item) => {
      if (key === item.parentPath || (key === "index" && "" === item.path)) {
        routes.push(item)
      }
    })
  }
  if (routes.length > 0) {
    permissionStore.setSidebarRoutes(routes)
  }

  return routes
}

onMounted(() => {
  window.addEventListener('resize', setVisibleNumber)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', setVisibleNumber)
})

onMounted(() => {
  setVisibleNumber()
})
</script>


<style lang="scss">
.topmenu-container.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}

.topmenu-container.el-menu--horizontal > .el-menu-item.is-active, .el-menu--horizontal > .el-sub-menu.is-active .el-sub-menu__title {
  border-bottom: 2px solid #{'var(--theme)'} !important;
  color: #303133;
}

/* submenu item */
.topmenu-container.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}
</style>
